{% extends "base.html" %}
{% block content %}

<h2> {{ poll.title }} </h2>
{% if poll_variants %}
<ul>
<form method="get" action="">
    {% for one in poll_variants %}
        <li>
        <input type="radio" name="poll_{{poll.id}}" value="{{one.id}}">
        {{one.text}}
       
        </li>
    {% endfor %}
</ul>
<input type="submit" value="Голосовать">
</form>
{% endif %}
{{ vote_result }}
{% if poll_results %}
    <ul>
    {% for one in poll_results %}
        <li>{{one.text}}: {{one.count}}</li>
    {% endfor %}
    </ul>
{% endif %}

<div id="upoll_container">
</div>
<script type="text/javascript">
    console.log('start');
    var poll_id = {{poll.id}};

    function load_poll_data(callback_func) {
        console.log('load_poll_data');
        url = "http://unblog.ichf.dyndns.info/polls/ajax/poll_data/"+poll_id+"?callback=?";
        console.log('requesting jsonp: '+url);
        $.ajax({
            url: url,
            dataType: 'jsonp',
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log('load_poll_data error: '+textStatus+'/'+errorThrown);
            },
            success: function(data){
                set_poll_variants(data);
            }
        });
    };

    /* 
        принимает массив с данными о голосовании, устанавливает html в upoll_container
    */
    function set_poll_variants(data) {
        console.log('set_poll_variants')
        variants = data.variants;
        var html = '';
        html += '<ul>';
        for (i=0; i<variants.length; i+=1) {
            var row = variants[i];
            var row_html = '';
            row_html += '<li>';
            row_html += '<input type="radio" name="poll_'+poll_id+'" value="'+row.variant_id+'">';
            row_html += row.text;
            row_html += '</li>';
            html += row_html;
        };
        html += '</ul>';
        html += '<a onclick="send_vote();">Отправить</a>';
        document.getElementById('upoll_container').innerHTML = html;
    };
    load_poll_data(set_poll_variants);
</script>

{% endblock %}
